#include "MagickCore/MagickCore.h"
#include "MagickCore/magic.h"
#include "MagickCore/magick-type.h"
#include "MagickCore/resize.h"
#include "string.h"

int _initializes() {
    MagickCoreGenesis(NULL, MagickTrue);
    return 1;
}

int _destroys() {
    MagickCoreTerminus();
    return 1;
}

int _convert(char *filename, char *output, int width, int height) {

    int ret = 0;

    ExceptionInfo *exception = AcquireExceptionInfo();

    ImageInfo *imageInfo;
    imageInfo = CloneImageInfo((ImageInfo *)NULL);
    strcpy(imageInfo->filename, filename);

    Image *images;
    images = ReadImage(imageInfo, exception);

    if (exception->severity != UndefinedException)
        CatchException(exception);

    if (images != (Image *)NULL) {
        Image *image, *resizedImage;
        image = RemoveFirstImageFromList(&images);

        if (image != NULL) {
            width = width == 0 ? 200 : width;
            if (height == 0) {
                float rate = (float)width / (float)image->columns;
                height = (int)(image->rows * rate);
                height = height == 0 ? 200 : height;
            }
            resizedImage =
                ResizeImage(image, width, height, LanczosFilter, exception);
            DestroyImage(image);
            if (resizedImage == (Image *)NULL) {
                MagickError(exception->severity, exception->reason,
                            exception->description);
                ret = 0;
            } else {
                strcpy(resizedImage->filename, output);
                WriteImage(imageInfo, resizedImage, exception);
            }

            DestroyImageInfo(imageInfo);
            ret = 1;
        }
    } else {
        ret = 0;
    }

    DestroyExceptionInfo(exception);

    return ret;
}
